

import { MemoryRouter } from 'react-router-dom'
import { ConfigProvider } from '@/components/base';
import type React from 'react';
import zhCN from 'antd/locale/zh_CN';
import ReactDOMClient from 'react-dom/client'
import stores from '@/stores';
import { themeConfig } from '@/constant/theme-config';
import dayjs from 'dayjs';

/** 挂在组件到跟上 */
export function mounting(node: React.ReactNode, id = `ID${dayjs().valueOf()}`) {
    // 使用 createRoot 而不是 hydrateRoot
    const root = ReactDOMClient.createRoot(getContainer(id));
    
    root.render(
        <ConfigProvider locale={zhCN} theme={stores?.themeConfig?.theme || themeConfig.get('dsff-default')?.theme}>
            <MemoryRouter>
                {node}
            </MemoryRouter>
        </ConfigProvider>
    );

    return () => {
        const container = document.getElementById(id);
        if (container) {
            root.unmount();
            container.remove();
        }
    };
}
// export function mounting(node: React.ReactNode, id = `ID${dayjs().valueOf()}`) {

//     const root = ReactDOMClient.hydrateRoot(getContainer(id), (
//         <ConfigProvider locale={zhCN} theme={stores?.themeConfig?.theme || themeConfig.get('dsff-default')?.theme} >
//             <MemoryRouter>
//                 {node}
//             </MemoryRouter>
//         </ConfigProvider>
//     ))

//     return () => {
//         const container = getContainer(id);
//         if (container) {
//             root.unmount();
//             container.remove();
//         }
//         const existingDiv = document.querySelector(`#${id}`);
//         if (existingDiv) {
//             existingDiv.remove();
//         }
//     }
// }

function getContainer(id: string) {
    return document.querySelector(`#${id}`) || createElement(id);
}

function createElement(id: string) {
    const div = document.createElement("div")
    div.id = id;
    div.style.zIndex = '9999';
    document.body.appendChild(div);
    return div;
}